package cn.ii8080.i8.oauth2.server.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.sql.DataSource;

@Configuration
public class TokenConfig {
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource dataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        System.out.println(druidDataSource);
        return druidDataSource;
    }

//    @Bean
//    public JwtAccessTokenConverter jwtAccessTokenConverter() {
//        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
//        ClassPathResource oauth2Jks = new ClassPathResource("oauth2.jks");
//        KeyStoreKeyFactory keyFactory = new KeyStoreKeyFactory(oauth2Jks, "oauth2".toCharArray());
//        converter.setKeyPair(keyFactory.getKeyPair("oauth2"));
//        return converter;
//    }

    /**
     * @return
     */
    @Bean
    public TokenStore tokenStore() {
        //通过redis管理令牌
        return new RedisTokenStore(redisConnectionFactory);
        //通过JDBC管理令牌
        //return new JdbcTokenStore(dataSource());
        // return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    public RandomValueAuthorizationCodeServices redisAuthorizationCodeServices() {
        return new JdbcAuthorizationCodeServices(dataSource());
    }
}
